<template>
  <section class="content clear">
    <section class="inner-top">
      <span class="detail-back" @click="back">角色管理</span><span style="margin:0px 3px">></span><span>{{roleName}}</span>
    </section>
    <section class="inner-bottom">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>应用分配</span>
            </div>
            <el-row>
              <el-col :span="24">
                <el-select v-model="selectCurrentAppIds" filterable multiple placeholder="请选择(可输入搜索)">
                  <el-option v-for="(item,index) in restaurants" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <el-button style="padding: 3px 0;height:30px;line-height:30px;" type="text" @click="addAppToRole">添加</el-button>
                <el-button style="padding: 3px 0;height:30px;line-height:30px;color:red;" type="text" @click="delAppToRole">删除</el-button>
              </el-col>
              <el-col :span="24" style="margin-top:20px;">
                <p class="appListClass" v-for="(item,index) in appList" :key="index" @click="appNodeClick(item.id)" :class="{'activeText':item.id === currentAppId}">{{item.name}}</p>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>菜单/路由分配</span>
              <!-- <el-button style="float: right; padding: 3px 0" type="text">保存</el-button> -->
            </div>
            <div>
              <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="菜单" name="1">
                  <el-tree :data="allMeauData" v-if="activeName === '1'" @check-change="meauOrRouterCheckChange" @node-click="meauAndRouterClick" :check-strictly="true" show-checkbox default-expand-all node-key="id" ref="meauTree" highlight-current :props="{label:'title',children:'children'}">
                  </el-tree>
                </el-tab-pane>
                <el-tab-pane label="路由" name="2">
                  <el-tree :data="allRouterData" v-if="activeName === '2'" @check-change="meauOrRouterCheckChange" @node-click="meauAndRouterClick" :check-strictly="true" show-checkbox default-expand-all node-key="id" ref="routerTree" highlight-current :props="{label:'title',children:'children'}">
                  </el-tree>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>按钮分配</span>
            </div>
            <div>
              <el-tree :data="allButtonData" @check-change="buttonCheckChange" :check-strictly="true" show-checkbox default-expand-all node-key="id" ref="buttonTree" highlight-current :props="{label:'name',children:'children'}">
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </section>
  </section>
</template>
<script>
import {createRoleAndAppRelationUsingGET, createRoleAndAppRelationUsingPOST,
  getAppAllByClassIdPOST, findMenuByRoleIdAndAppIdUsingGET, getMeauByAppRole,
  createRoleAndRouterRelationUsingPOST, getRouterByAppRole, findRouterByRoleIdAndAppIdUsingDELETE, getRouterNotMeauGET,
  setButtonsForRole, delButtonsForRole, getHasButtonsForRoleAndApp, delRoleAndAppRelationUsingDELETE,
  getButtonsByRouterId} from '@api/systemManage'
export default {
  name: 'addApplication',
  data () {
    return {
      roleName: null,
      roleId: null, // 角色ID
      restaurants: [],
      currentAppId: null, // 当前选择应用
      selectCurrentAppIds: [], // 应用id集合
      currentSearchAppName: null,
      currentSearchAppId: null, // 搜索应用id
      activeName: '1',
      appList: [],
      allMeauData: [], // 菜单
      hasSetMeau: [], // 已经设置菜单
      allRouterData: [], // 路由
      hasSetRouter: [], // 已经设置路由
      allButtonData: [], // 按钮
      hasSetButton: [], // 已有按钮
      currentMeauOrRouterId: null
    }
  },
  watch: {
    currentAppId (val) { // 当前应用id变化时触发
      this.getCurrentAppMeau()
    },
    activeName (val) { // 菜单路由切换时触发
      if (val === '1') { // 菜单
        this.getCurrentAppMeau()
      } else { // 路由
        this.getCurrentAppRouter()
      }
    },
    // 当前路由菜单id变化时更新按钮
    currentMeauOrRouterId (val) {
      this.allButtonData = []
      if (val) {
        this.getAllButtonByRouterId()
      } else {
        this.$refs.buttonTree.setCheckedKeys([])
      }
    }
  },
  created () {
    this.roleId = Number(this.$route.query.id)
    this.roleName = this.$route.query.roleName
    this.getAppByRole()
    this.getAllAppList()
  },
  methods: {

    // 获取当前路由、菜单下面的已添加按钮
    getHasButtonByRouterOrMeau () {
      this.hasSetButton = []
      getHasButtonsForRoleAndApp(this.roleId, this.currentAppId, this.currentMeauOrRouterId).then(res => {
        if (res.status && res.data.length) {
          this.hasSetButton = this.getid(res.data)
        }
        this.$refs.buttonTree.setCheckedKeys(this.hasSetButton)
      })
    },
    // 获取点击路由、菜单下面的所有按钮（包括未授权）
    getAllButtonByRouterId () {
      getButtonsByRouterId(this.currentMeauOrRouterId, 1, 100000).then(res => {
        if (res.status) {
          this.allButtonData = res.data.list
          this.getHasButtonByRouterOrMeau()
        }
      })
    },
    // 根据菜单路由获取按钮
    meauAndRouterClick (val) {
      this.currentMeauOrRouterId = val.id
    },
    buttonCheckChange (data, isSelect) {
      if (isSelect && this.hasSetButton.indexOf(data.id) === -1 && this.currentMeauOrRouterId) { // 添加授权当前按钮
        setButtonsForRole(this.roleId, [data.id]).then(res => {
          // this.$message.success('授权成功')
          this.getHasButtonByRouterOrMeau()
        })
      } else if (!isSelect && this.hasSetButton.indexOf(data.id) > -1 && this.currentMeauOrRouterId) { // 取消授权当前按钮
        delButtonsForRole(this.roleId, [data.id]).then(res => {
          // this.$message.success('取消授权成功')
          this.getHasButtonByRouterOrMeau()
        })
      }
    },
    // 点击应用节点
    appNodeClick (id) {
      this.activeName = '1'
      this.currentAppId = id
    },
    meauOrRouterCheckChange (nodeVal, isSelect, selectData) {
      let params = [nodeVal.id]
      if (!isSelect && this.hasSetMeau.indexOf(nodeVal.id) > -1 && this.activeName === '1') { // 取消某个菜单权限
        this.cancleRouterRole(params)
      } else if (!isSelect && this.hasSetRouter.indexOf(nodeVal.id) > -1 && this.activeName === '2') { // 取消某个路由权限
        this.cancleRouterRole(params)
      } else if (this.activeName === '1' && this.hasSetMeau.indexOf(nodeVal.id) === -1) { // 添加某个权限
        this.addRouterForRole(params)
      } else if (this.activeName === '2' && this.hasSetRouter.indexOf(nodeVal.id) === -1) {
        this.addRouterForRole(params)
      }
    },
    // 取消授权某路由，菜单
    cancleRouterRole (routerIds) {
      findRouterByRoleIdAndAppIdUsingDELETE(this.roleId, routerIds).then(res => {
        if (res.status) {
          // this.$message.success('取消成功')
          this.getHasAddMeauForRole()
        }
      })
    },
    // 授权某角色某个路由、菜单
    addRouterForRole (routerIds) {
      createRoleAndRouterRelationUsingPOST(this.roleId, routerIds).then(res => {
        if (res.status) {
          // this.$message.success('设置成功')
          if (this.activeName === '1') {
            this.getHasAddMeauForRole()
          } else {
            this.getHasAddRouterForRole()
          }
        }
      })
    },

    getid (list, newList = []) {
      list.map(item => {
        newList.push(item.id)
        if (item.children && item.children.length > 0) {
          this.getid(item.children, newList)
        }
      })
      return [...newList]
    },
    // 获取当前应用的菜单
    getCurrentAppMeau () {
      findMenuByRoleIdAndAppIdUsingGET(this.currentAppId).then(res => {
        if (res.status && res.data.length) {
          this.allMeauData = this.dealTreeData(res.data) // 解决相同title的；将title与路由name拼接
          this.currentMeauOrRouterId = this.allMeauData[0].id
          this.getHasAddMeauForRole()
        } else {
          this.allMeauData = []
          this.currentMeauOrRouterId = null
        }
      })
    },
    dealTreeData (treeData) {
      return treeData.map(item => {
        item.title = `${item.title}(${item.name})`
        if (item.children && item.children.length > 0) {
          this.dealTreeData(item.children)
        }
        return item
      })
    },
    // 获取已设置菜单
    getHasAddMeauForRole () {
      this.hasSetMeau = []
      getMeauByAppRole(this.roleId, this.currentAppId).then(res => {
        if (res.status && res.data.length) {
          this.hasSetMeau = this.getid(res.data) // 获取已添加路由(菜单)id
          this.$refs.meauTree.setCheckedKeys(this.hasSetMeau)
        }
      })
    },
    // 获取当前应用的路由
    getCurrentAppRouter () {
      // 目前缺少只获取路由（非菜单）接口
      getRouterNotMeauGET(this.currentAppId).then(res => {
        if (res.status && res.data.length) {
          this.allRouterData = this.dealTreeData(res.data) // 解决相同title的；将title与路由name拼接
          this.currentMeauOrRouterId = this.allRouterData[0].id
          this.getHasAddRouterForRole()
        } else {
          this.allRouterData = []
          this.currentMeauOrRouterId = null
        }
      })
    },
    // 获取已设置路由
    getHasAddRouterForRole () {
      getRouterByAppRole(this.roleId, this.currentAppId).then(res => {
        if (res.status && res.data.length) {
          this.hasSetRouter = this.getid(res.data) // 获取已添加路由(菜单)id
          this.$refs.routerTree.setCheckedKeys(this.hasSetRouter)
        } else {
          this.hasSetRouter = []
        }
      })
    },
    // 获取所有应用列表
    getAllAppList () {
      getAppAllByClassIdPOST({}).then(res => {
        if (res.status && res.data.length) {
          this.restaurants = res.data
        }
      })
    },
    // 获取某个角色已添加所有应用
    getAppByRole () {
      createRoleAndAppRelationUsingGET(this.roleId).then(res => {
        if (res.status) {
          this.appList = res.data
          this.currentAppId = res.data[0].id
        }
      })
    },
    // 角色添加应用
    addAppToRole () {
      createRoleAndAppRelationUsingPOST(this.roleId, this.selectCurrentAppIds).then(res => {
        if (res.status) {
          this.getAppByRole()
        }
      })
    },
    // 删除角色某个应用
    delAppToRole () {
      if (this.currentAppId) {
        this.$confirm('此操作将取消所选择应用授权, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        // 20191111接口还在写
          delRoleAndAppRelationUsingDELETE(this.roleId, this.selectCurrentAppIds).then(res => {
            if (res.status) {
              this.getAppByRole()
              this.$message.success('删除成功')
            }
          })
        }).catch(() => {

        })
      } else {
        this.$message.warning('请选择删除的应用')
      }
    },
    back () {
      this.$router.push({name: 'roleManage'})
    },
    handleTabClick (val) {
      console.log(val)
    }
  }
}
</script>
<style lang="less" scoped>
.appListClass {
  text-align: left;
  padding: 5px;
  cursor: pointer;
}
.activeText {
  color: #409eff;
}
</style>
